use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::{Aes128Gcm, Key, Nonce};
use base64;
use hex;
use rand::Rng;
use rand::rngs::OsRng;
use crate::handlers::DeviceParams;

pub fn new_device_params() -> DeviceParams {
    let mut rng = OsRng;

    let dev_addr: [u8; 4] = rng.gen();
    let dev_addr = hex::encode(dev_addr);

    let nwk_skey: [u8; 16] = rng.gen();
    let nwk_skey = hex::encode(nwk_skey);

    let app_skey: [u8; 16] = rng.gen();
    let app_skey = hex::encode(app_skey);

    let join_nonce: [u8; 3] = rng.gen();
    let join_nonce = hex::encode(join_nonce);

    DeviceParams {
        dev_eui: "".to_string(),
        app_eui: "".to_string(),
        app_key: "".to_string(),
        dev_nonce: "".to_string(),
        dev_addr,
        nwk_skey,
        app_skey,
        join_nonce,
    }
}

pub fn encrypt(params: &DeviceParams, app_key: &str) -> String {
    // 验证 app_key 是否是有效的十六进制字符串并且长度为 32 个字符
    if app_key.len() != 32 || app_key.chars().any(|c| !c.is_ascii_hexdigit()) {
        panic!("app_key 的十六进制格式无效或长度不正确: {}", app_key);
    }
    
    // 解码 app_key 为字节数组
    let app_key_bytes = hex::decode(app_key).expect("解码 app_key 失败");

    // 验证解码后的字节数组长度
    if app_key_bytes.len() != 16 {
        panic!("解码后的 app_key 长度不正确: {}", app_key_bytes.len());
    }
    
    // 创建一个16字节的数组并复制解码后的字节
    let mut key_bytes = [0u8; 16];
    key_bytes.copy_from_slice(&app_key_bytes);

    // 使用 Aes128Gcm 需要的 Key 类型
    let key = Key::from_slice(&key_bytes);
    let cipher = Aes128Gcm::new(key);

    // 明确指定 nonce 的长度为 12 字节
    let nonce = Nonce::from_slice(b"unique nonce"); // 12 字节的 nonce

    let plaintext = format!(
        "{}{}{}{}",
        params.dev_addr, params.nwk_skey, params.app_skey, params.join_nonce
    );
    let ciphertext = cipher
        .encrypt(nonce, plaintext.as_bytes())
        .expect("encryption failure!");

    base64::encode(ciphertext)
}
